package com.atguigu.flink.window.all;

import com.atguigu.flink.pojo.WaterSensor;
import com.atguigu.flink.util.MyUtil;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.ProcessingTimeSessionWindows;
import org.apache.flink.streaming.api.windowing.assigners.SlidingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.assigners.TumblingProcessingTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

/**
  基于ProcessingTime演示
 */
public class Demo3_TimeWindow
{
    public static void main(String[] args) {


        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        env
            .socketTextStream("hadoop103", 8888)
            .map(new MapFunction<String, WaterSensor>()
           {
               @Override
               public WaterSensor map(String value) throws Exception {
                   String[] data = value.split(",");
                   return new WaterSensor(
                       data[0],
                       Long.valueOf(data[1]),
                       Integer.valueOf(data[2])
                   );
               }
           })
            //滚动窗口
            //.windowAll(TumblingProcessingTimeWindows.of(Time.seconds(5)))
            //滑动
            //.windowAll(SlidingProcessingTimeWindows.of(Time.seconds(5),Time.seconds(3)))
            //会话窗口
            .windowAll(ProcessingTimeSessionWindows.withGap(Time.seconds(5)))
            .process(new ProcessAllWindowFunction<WaterSensor, String, TimeWindow>()
            {
                @Override
                public void process(Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {

                    //获取窗口的时间信息
                    TimeWindow window = context.window();

                    System.out.println(MyUtil.parseTimeWindow(window));

                    out.collect(MyUtil.parseList(elements).toString());
                }
            })
            .print();

        try {
                    env.execute();
                } catch (Exception e) {
                    e.printStackTrace();
                }

    }
}
